//
//  IndexViewController.m
//  CarLifes
//
//  Created by yu on 2017/8/4.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "IndexViewController.h"
#import "LocationAnnotationView.h"
#import "ClusterAnnotationView.h"
#import "SettingViewController.h"

#import "SearchTraceViewController.h"
#import "TracingViewController.h"
#import "UserInfoViewController.h"
#import "AlarmViewController.h"
#import "RoutePlanViewController.h"
#import "TraceModel.h"
#import "TabBarController.h"
#import "UIView+TransitionAnimation.h"
#import "ModifyPsdViewController.h"

#import "ErrorInfoUtility.h"
#import "Utility.h"
#import "LocationManager.h"


#define kReuseIndetifier @"AnnotationReuseIndetifier"
#define kSendBtnTitleNotification @"kSendBtnTitleNotification"


@interface IndexViewController ()
{
    CGPoint _selectPoint;
    
    LocationAnnotationView *_locationAnnotationView;
}

@property (nonatomic, strong) TraceModel *traceModel;

@property (nonatomic, strong) EquipmentModel *annotation;

@property (nonatomic, strong) ClusterAnnotationView *annotationView;

@end

@implementation IndexViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = [self.dataSource.firstObject ownerName];
    
    [self initMapView];
    
    [self setupButton];
    
    [self addAnnotation];
    
    self.userLocBtn.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToNextController:) name:kSendBtnTitleNotification object:nil];
    
    [self setRightItemTitle:@"修改密码" action:@selector(changePsdAction)];
}

- (void)changePsdAction
{
    ModifyPsdViewController *psd = [[ModifyPsdViewController alloc] init];
    psd.dataSource = self.dataSource;
    [self.navigationController pushViewController:psd animated:YES];
}

- (void)pushToNextController:(NSNotification *)noti
{
    NSInteger btnTag = [noti.userInfo[@"tag"] integerValue];
    
    EquipmentModel *model = [noti object];
    
    switch (btnTag)
    {
        case FuncKeyTypeReplayTrace:
        {/** 历史轨迹*/
            SearchTraceViewController *chooseTime = [[SearchTraceViewController alloc] init];
            chooseTime.eqNo = model.eqNo;
            chooseTime.ownerName = model.ownerName;
            [self.navigationController pushViewController:chooseTime animated:YES];
        }
            break;
        case FuncKeyTypeRelocation:
        {/** 重新定位*/
            [self loadEquipLatestInfo:model.eqNo];
        }
            break;
        case FuncKeyTypeTracing:
        {/** 实时跟踪*/
            TracingViewController *tracing = [[TracingViewController alloc] init];
            tracing.eqNo = model.eqNo;
            tracing.ownerName = model.ownerName;
            tracing.cnStatus = model.cnStatus;
            tracing.isNeedDeptId = NO;
            [self.navigationController pushViewController:tracing animated:YES];
        }
            break;
        case FuncKeyTypeUserInfo:
        {/** 用户信息*/
            UserInfoViewController *userInfo = [[UserInfoViewController alloc] init];
            userInfo.eqNo = model.eqNo;
            userInfo.isNeedDeptId = NO;
            [self.navigationController pushViewController:userInfo animated:YES];
        }
            break;
        case FuncKeyTypeDeviceAlarm:
        {/** 设备报警*/
            AlarmViewController *alarm = [[AlarmViewController alloc] init];
            alarm.eqNo = model.eqNo;
            alarm.egId = model.egId;
            [self.navigationController pushViewController:alarm animated:YES];
        }
            break;
        case FuncKeyTypeNavigator:
        {/** 一键追车*/
            RoutePlanViewController *navigation = [[RoutePlanViewController alloc] init];
            navigation.destinationPoint = [[CLLocation alloc] initWithLatitude:[self.traceModel.gdLat doubleValue] longitude:[self.traceModel.gdLng doubleValue]];
            [self.navigationController
             pushViewController:navigation animated:YES];
        }
            break;
        default:
            break;
    }
}

- (void)addAnnotation
{
    NSMutableArray *coordinates = [NSMutableArray array];
    for (int i = 0; i < self.dataSource.count; i++) {
        EquipmentModel *eModel = self.dataSource[i];
        eModel.coordinate = CLLocationCoordinate2DMake([eModel.pointModel.lat doubleValue],[eModel.pointModel.lng doubleValue]);
        [coordinates addObject:eModel];
    }
    [self.mapView addAnnotations:coordinates];
    [self.mapView showAnnotations:coordinates edgePadding:UIEdgeInsetsMake(90, 70, 70, 70) animated:YES];
}

/* 加载最新的设备信息 */
- (void)loadEquipLatestInfo:(NSString *)eqNo
{
    [self.requestTool loadRealTrackByEqno:eqNo show:YES success:^(TraceModel *traceModel) {
        self.traceModel = traceModel;
        
        ///<1>.逆地理编码
        [self searchReGeocodeWithCoordinate:CLLocationCoordinate2DMake([traceModel.gdLat doubleValue], [traceModel.gdLng doubleValue])];
        
        ///<2>.刷新标注点的位置
        [self.annotation setCoordinate:CLLocationCoordinate2DMake([traceModel.gdLat doubleValue], [traceModel.gdLng doubleValue])];
        
        ///<3>.刷新地图中心点
        [self.mapView setCenterCoordinate:self.annotation.coordinate];
        
    } failure:^(NSError *error) {
        PPLog(@"load real track error = %@",error);
    }];
}

- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    [ReGeocodeManager searchReGeocodeWithCoordinate:coordinate reGeocodeBlock:^(AMapReGeocode *reGeocode) {
        AMapPOI *poi = reGeocode.pois[0];
        NSString *format = reGeocode.formattedAddress;
        NSString *poiname = poi.name;
        
        if ([format containsString:poiname]) {
            poiname = @"";
        }
        
        self.traceModel.address = NSStringFormat(@"%@%@ %@ %ldm",format,poiname,[Utility turnDirection:poi.direction],poi.distance);
        [self.annotationView setTraceModel:self.traceModel];
    } reGeocodeFailBlock:^(NSString *errcode) {
        self.traceModel.address = errcode;
        [self.annotationView setTraceModel:self.traceModel];
    }];
}

- (void)magnify:(UIButton *)sender
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom + 1) animated:YES];
}

- (void)shrink:(UIButton *)sender
{
    CGFloat oldZoom = self.mapView.zoomLevel;
    [self.mapView setZoomLevel:(oldZoom - 1) animated:YES];
}

#pragma mark - MAMapViewDelegate - 
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    /* 自定义userLocation对应的annotationView */
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[LocationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:userLocationStyleReuseIndetifier];
            
            annotationView.canShowCallout = YES;
        }
        
        _locationAnnotationView = (LocationAnnotationView *)annotationView;
        [_locationAnnotationView updateImage:[UIImage imageNamed:@"userPosition"]];
        
        return annotationView;
    }
    
    if ([annotation isKindOfClass:[EquipmentModel class]]){
        
        ClusterAnnotationView *annotationView = (ClusterAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:kReuseIndetifier];
        
        if (annotationView == nil) {
            annotationView = [[ClusterAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kReuseIndetifier];
        }
        self.annotationView = annotationView;
        
        [annotationView setCanShowCallout:NO];
        
        [annotationView setDataSource:self.dataSource];
        
        return annotationView;
    }
    return nil;
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    /* 自定义定位精度对应的MACircleView */
    if (overlay == mapView.userLocationAccuracyCircle)
    {
        MACircleRenderer *accuracyCircleRenderer = [[MACircleRenderer alloc] initWithCircle:(MACircle *)overlay];
        
        accuracyCircleRenderer.strokeColor  = kMAOverlayRendererDefaultStrokeColor;
        accuracyCircleRenderer.fillColor    = [kBaseColor colorWithAlphaComponent:0.1];
        
        return accuracyCircleRenderer;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    
    if ([view.annotation isKindOfClass:[EquipmentModel class]])
    {
        EquipmentModel *annotation = (EquipmentModel *)view.annotation;
        self.annotation = annotation;
        self.annotationView = (ClusterAnnotationView *)view;
//        PPLog(@"select annotation for \n eqNo = %@ \n status = %@",annotation.eqNo,annotation.status);
        PPLog(@"99999 = %@",annotation.cnStatus);
        CLLocationCoordinate2D selectCoordinate = annotation.coordinate;
        
        ///地图的视图锚点。坐标系归一化，默认为(0.5, 0.5)，即当前地图的视图中心
        MAMapStatus *status = [self.mapView getMapStatus];
        CGFloat scale = 0.00;
        if (kScreenHeight == 568) { // 5
            scale = 0.7;
        } else if (kScreenHeight == 667) { // 6
            scale = 0.7;
        } else if (kScreenHeight == 736) { // 6p
            scale = 0.63;
        }
        status.screenAnchor = CGPointMake(0.5,scale);
        
        [self.mapView setMapStatus:status animated:YES];
        [self.mapView setCenterCoordinate:selectCoordinate animated:YES];
        
        // 根据设备号加载最新的设备信息
        [self loadEquipLatestInfo:annotation.eqNo];
    }
    
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAMapStatus *status = [self.mapView getMapStatus];
        status.screenAnchor = CGPointMake(0.5,0.5);
        
        [self.mapView setMapStatus:status animated:YES];
        [mapView setCenterCoordinate:view.annotation.coordinate animated:YES];
    }
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if (!updatingLocation && _locationAnnotationView != nil)
    {
        _locationAnnotationView.rotateDegree = userLocation.heading.trueHeading - self.mapView.rotationDegree;
    }
}

//- (void)exitAction
//{
//    CLTabBarController *tab = [[CLTabBarController alloc] init];
//    [KEY_WINDOW addTransitionAnimationWithDuration:0.5f type:TransitionPageUnCurl subType:FROM_BOTTOM];
//    KEY_WINDOW.rootViewController = tab;
//}

//- (void)settingAction
//{
//    SettingViewController *setting = [[SettingViewController alloc] init];
//    [self.navigationController pushViewController:setting animated:YES];
//}


- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

@end
